<template>
    <el-dialog v-model="drawer" @close="close" :append-to-body="true" width="660px" title="客户阶段设置">
        <el-row>
            <el-button size="small" type="primary" @click="addStage">新增阶段类型</el-button>
        </el-row>
        <el-form :model="form" :rules="rules" label-width="0" class="drawer-form" ref="ruleFormRef">
            <el-table :data="list" size="small" border ref="headerTable" @select-all="selectEvent" @select="selectEvent">
                <el-table-column type="selection" width="30" fixed="left"></el-table-column>
                <el-table-column prop="name" label="阶段名称" width="208px">
                    <template #default="scope">
                        <span style="width:130px;display:inline-block;font-size:12px;">{{ scope.row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序"></el-table-column>
                <el-table-column label="操作" width="100px" align="center">
                    <template #default="scope">
                        <el-button size="small" link type="primary" @click="edit(scope.row)">编辑</el-button>
                        <el-button size="small" link type="primary" @click="del(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
        <el-row class="footer-fixed">
            <el-button type="primary" :loading="submitLoading" size="small" @click="submit(ruleFormRef)">提交</el-button>
            <el-button size="small" @click="cancel(ruleFormRef)">取消</el-button>
        </el-row>
    </el-dialog>

    <!-- 添加阶段弹窗 -->
    <el-dialog v-model="dialogCreate" :title="title" :append-to-body="true" @close="hideAddStage" width="300px">
        <el-form :model="addForm" :rules="rules" size="small" ref="ruleRefForm" label-width="70px">
            <el-form-item label="分类名称" prop="name">
                <el-input v-model="addForm.name" placeholder="请输入阶段名称" style="width:182px"></el-input>
            </el-form-item>
            <el-form-item label="显示" prop="status">
                <el-switch v-model="addForm.status" :active-value="1" :inactive-value="0" class="ml-2"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-row justify="center">
                <el-button size="small" type="primary" @click="submitAddForm(ruleRefForm)">提交</el-button>
                <el-button size="small" type="default" @click="hideAddStage(ruleRefForm)">取消</el-button>
            </el-row>
        </template>
    </el-dialog>
</template>
<script>
import { computed, reactive, toRefs, watch, ref, onMounted, onBeforeUpdate, onUpdated, onBeforeMount, nextTick } from 'vue'
import { EditPen, Check, Message } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '/@/api/commonApi'

export default {
    name: 'TableHeader',
    props: {
        dialogDrawer: {
            type: Boolean,
            default: false
        },
    },
    setup(props, context) {
        const { dialogDrawer, defaultStage } = toRefs(props)
        const ruleFormRef = ref()
        const headerTable = ref()
        // 控制提交按钮显示加载状态
        const submitLoading = ref(false)
        const state = reactive({
            // 当前选中的状态的 ids 列表
            selectStatusIds: [],
            dialogCreate: false,
            form: {
                header: []
            },
            list: [],
            rules: {},
            addForm: {
                name: '',
                type: 1,
                status: 1
            },
            checkAll: false,
            isIndeterminate: false,
            checkedHeader: ['customerName', 'contact', 'phone', 'product'],
            title: '',
        })


        let drawer = computed({
            get: () => dialogDrawer.value,
            set: (val) => {
                context.emit('update:dialogDrawer', val)
            }
        })



        watch(() => dialogDrawer.value,
            val => {
                getStageList()
                context.emit("update:dialogDrawer", val)
            }
        )
        const close = () => context.emit("update:dialogDrawer", false)
        // 提交保存
        const submit = async (formEl) => {
            if (state.selectStatusIds.length > 0) {
                // 进行修改
                submitLoading.value = true
                api.updateShowList({ ids: state.selectStatusIds + '' }).then(res => {
                    ElMessage.success("编辑成功")
                })
                submitLoading.value = false
                context.emit('onShowStage', true)
                context.emit("update:dialogDrawer", false)
            } else {
                ElMessage.error("至少显示一条")
            }
        }
        const cancel = (formEl) => {
            context.emit('onShowStage', true)
            context.emit("update:dialogDrawer", false)
        }
        // 当用户手动勾选数据行的 Checkbox 时触发的事件
        // 当用户手动勾选全选 Checkbox 时触发的事件
        const selectEvent = (e) => {
            // 针对选中的进行保存
            state.selectStatusIds = e.map(s => s.id)
        }
        const addReset = () => {
            state.addForm = {
                name: '',
                type: 1,
                status: 1
            }
        }
        // 新增阶段类型
        const addStage = () => {
            addReset()
            state.title = '添加阶段活动'
            state.dialogCreate = true
        }
        // 取消添加阶段
        const hideAddStage = () => {
            addReset()
            state.dialogCreate = false
        }
        // 获取全部阶段
        const getStageList = () => {
            state.selectStatusIds = []
            api.stageList({}).then(res => {
                headerTable.value.clearSelection()
                state.list = res.data
                nextTick(() => {
                    state.list.forEach(item => {
                        if (item.status == '1') {
                            headerTable.value.toggleRowSelection(item, true)
                            state.selectStatusIds.push(item.id)
                        }
                    })
                })
            })
        }
        // 添加阶段
        const submitAddForm = () => {
            if (state.addForm.name == '' || state.addForm.name == null) {
                ElMessage.error("请输入阶段名称")
            } else {
                if (state.title == '添加阶段活动') {
                    api.addStage(state.addForm).then(res => {
                        ElMessage.success("添加成功")
                        addReset()
                        getStageList()
                        state.dialogCreate = false
                    })
                } else {
                    api.editStage(state.addForm).then(res => {
                        ElMessage.success("编辑成功")
                        addReset()
                        getStageList()
                        state.dialogCreate = false
                    })
                }
            }
        }
        // 编辑
        const edit = (item) => {
            state.title = '编辑阶段活动'
            state.addForm = item
            state.dialogCreate = true
        }
        // 删除
        const del = (item) => {
            ElMessageBox.confirm(`是否确认删除「${item.name}」?`, '提示',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                api.delStage({ ids: item.id }).then(res => {
                    ElMessage.success("删除成功")
                    getStageList()
                })
            })
        }
        return {
            drawer,
            ...toRefs(state),
            close,
            edit,
            del,
            ruleFormRef,
            submit,
            cancel,
            addStage,
            EditPen,
            Check,
            getStageList,
            hideAddStage,
            submitAddForm,
            headerTable,
            selectEvent,
            submitLoading
        }
    }
}
</script>

<style scoped lang="scss">
.drawer-form {
    padding: 10px 10px 64px;
}

.footer-fixed {
    position: absolute;
    left: 0;
    bottom: 0;
    right: 0;
    padding: 10px;
    background: #fff;
    z-index: 999;
    display: flex;
    justify-content: center;
    box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px;
}
</style>